// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let { id } = event
  var success = false
  var message = "删除失败"
  const db = cloud.database()
  var cards = await db.collection('cards').where({
    _id: id
  }).get()

  if (cards.data.length != 0) {
    await db.collection('cards').where({
      _id: id
    }).remove().then(res => {
      success = true
      message = "删除成功"
    }, error => {
      success = false
      message = "删除失败，请联系管理员"
    })
  }

  let card = cards.data[0];
  if (success && card.status == 'checked') {
    let user = await db.collection('user').where({
      _openid: card._openid
    }).get()
    let point = user.data[0].point  <= 0 ? 0 :user.data[0].point - card.point;
    let weekPoint = user.data[0].weekPoint <=0 ? 0 : user.data[0].weekPoint- card.point
    await db.collection('user').where({
      _openid: card._openid
    }).update({
      data: {
        point: point,
        weekPoint
      }
    }).then(res => {
      console.log('res', res)
      success = true
      message = "删除成功"
    }, error => {
      console.log('error', error)
      success = false
      message = "删除失败，请联系管理员"
    })
  }

  var userData = await db.collection('userInfo').where({
    _openid: card._openid
  }).get()
  let userInfo = userData.data[0]
  var distance = card.distance;
  if (!distance) {
    distance = 0
  }
  var time = card.time;
  if (!time) {
    time = 0
  }
  var calorie = card.calorie;
  if (!calorie) {
    calorie = 0
  }
  if (success && card.status == 'checked' && userInfo) {
    distance = parseFloat(userInfo.distance)<=0 ? 0 :parseFloat(userInfo.distance) - parseFloat(distance)
    distance = distance.toFixed(2)
    time = parseInt(userInfo.time) <=0 ? 0 : parseInt(userInfo.time) - parseInt(time)
    calorie = parseInt(userInfo.calorie)<=0 ? 0 :parseInt(userInfo.calorie) - parseInt(calorie)
    point = parseInt(userInfo.point)<= 0 ? 0 : parseInt(userInfo.point) - parseInt(card.point)
    await db.collection('userInfo').where({
      _openid: card._openid
    }).update({
      data: {
        point: point,
        distance: distance,
        calorie: calorie,
        time: time
      },
    }).then(res => {
      console.log('res', res)
      success = true
      message = "删除成功"
    }, error => {
      console.log('error', error)
      success = false
      message = "删除失败，请联系管理员"
    })
  }
  

  return {
    success: success,
    message: message
  }
}